import { Devices } from "../../devices";
import {commends} from "../../commends";
import drawQrcode from "../../weapp-qrcode.esm";

Page({
    data: {
        statusBarHeight: 44,
        //是否正在发现设备
        discovering: false,
        //设备列表
        devices: [],
        //已选设备
        selected_deviceId: "",
        //规定仅显示哪些名称的设备
        device_name: null
    },
    //由页面传送过来的打印对象
    printer: null,
    //是否自动连接上次保存的设备，并打印
    auto_print: false,
    //
    BLEPrinter_device_name: "BLEPrinter_device",
    //
    onLoad(options) {
        let self = this;
        options = options || {};
        //自定义设备名称（仅查询该名称的设备）
        let dn = options.device_name || null;
        if(dn !== null && dn !== ""){
            this.setData({
                device_name: dn
            });
        }
        //是否连接到上次连接的设备，然后自动打印
        let ap = options.auto_print || null;
        this.auto_print = ap == "true" || ap == 1;
        //
        const eventChannel = this.getOpenerEventChannel() || null;
        if(eventChannel && eventChannel.on){
            eventChannel.on("setPrinter", printer => {
                self.printer = printer;
                if(self.auto_print){
                    //需要自动打印，从缓存中获取
                    let deviceId = wx.getStorageSync(self.BLEPrinter_device_name);
                    if(deviceId != null && deviceId != undefined && deviceId != ""){
                        if(self.data.discovering){
                            //停止发现设备
                            self.stopDiscover();
                        }
                        //尝试连接设备
                        Devices.connectDevice(deviceId, res => {
                            if(!res.error){
                                //连接设备成功，可以自动打印
                                self.setData({
                                    selected_deviceId: deviceId,
                                    devices: [
                                        {
                                            deviceId: deviceId,
                                            name: "常用设备",
                                            connected: true
                                        }
                                    ]
                                },() => {
                                    //打印
                                    setTimeout(self.printTicket, 200);
                                });
                            }else{
                                //未能自动连接设备
                                console.log("未能自动连接设备：" + deviceId);
                                //移除历史记录
                                wx.removeStorageSync(self.BLEPrinter_device_name);
                            }
                        });
                    }else{
                        self.startDiscover();
                    }
                }
            });
        }
    },
    onUnload(){
        //页面离开的时候，清除所有
        if(this.data.selected_deviceId){
            Devices.disconnect(this.data.selected_deviceId);
        }
        Devices.stop();
    },
    onShow(){
        this.startDiscover();
    },
    onReady() {
        let self = this;
        //开始
        Devices.stop();
        Devices.start();
        //发现设备时
        Devices.onDeviceFound(device => {
            if(this.data.device_name === null || this.data.device_name === "" || device.name.toString().toUpperCase() === this.data.device_name){
                self.data.devices.push(device);
                self.setData({
                    devices: self.data.devices
                });
            }
        });
        //蓝牙已初始化
        Devices.onAdapterStateChange(res => {
            self.setData({
                discovering: res.discovering
            });
        });
        //设备断开连接
        Devices.onConnectionStateChange(res => {
            console.log(res.deviceId, res.connected ? "已连接" : "已断开");
            let devices = self.data.devices;
            let device = null;
            for(let i = 0; i<devices.length; i++){
                if(devices[i].deviceId === res.deviceId){
                    self.setData({
                        [`devices[${i}].connected`]: res.connected
                    });
                    device = devices[i];
                    device.connected = res.connected;
                }
            }
            if(device && res.connected){
                //更换
                wx.setStorageSync(self.BLEPrinter_device_name, device.deviceId);
            }
        });
    },
    //
    showMessage(text){
        wx.showModal({
            title: "提醒",
            content: text,
            showCancel: false,
            confirmText: "我知道了"
        });
    },
    //
    toggleDiscovery(){
        if(!this.data.discovering){
            this.startDiscover();
        }else{
            this.stopDiscover();
        }
    },
    //搜索开始
    startDiscover(){
        let self = this;
        Devices.discovery(res => {
            if(res.error){
                self.showMessage(res.message);
            }else {
                self.data.selected_deviceId = "";
            }
            self.setData({
                discovering: res.error === 0
            });
        });
    },
    //停止搜索
    stopDiscover(){
        let self = this;
        Devices.stopDiscovery(res => {
            if(res.error){
                self.showMessage(res.message);
            }
            self.setData({
                discovering: false
            });
        });
    },
    //选择
    selectDevice(e){
        const { id } = e.currentTarget.dataset;
        let device = Devices.getDeviceById(id);
        if(device !== null){
            this.setData({
                selected_deviceId: device.deviceId
            });
        }
        //停止发现设备
        this.stopDiscover();
    },
    //连接设备
    connectDevice(callback){
        if(this.data.device.deviceId !== "") {
            let self = this;
            Devices.connectDevice(this.data.device.deviceId, res => {
                if(res.error){
                    self.showMessage(res.message);
                }else{
                    //连接成功
                    self.setData({
                        device: res.device
                    });
                    if(typeof callback === "function"){
                        callback();
                    }
                }
            });
        }
        else{
            this.showMessage("先选择设备");
        }
    },
    //打印小票
    translateQueueDataFinish: false,
    printTicket(){
        if(!this.printer){
            this.showMessage("没有需要打印的数据");
            return;
        }
        if(!this.translateQueueDataFinish){
            //打印前，将打印队列中的数据，统一转换为打印数据，如果是图片、二维码，则需要特别处理
            this.printer.queue = Array.from(commends.HARDWARE.HW_INIT);
            this.translateQueueData();
        }else{
            this.exec();
        }
    },
    exec(){
        let selected_deviceId = this.data.selected_deviceId;
        let self = this;
        if(selected_deviceId != ""){
            wx.showModal({
                title: "打印提醒",
                content: "正在打印，请勿关闭页面，请等待小票打印完成后，再离开此页面，以免打印未完成。",
                cancelText: "知道了",
                confirmText: "打印结束",
                success: res =>{
                    if(res.confirm){
                        //路由返回
                        wx.navigateBack();
                    }
                }
            });
            this.printer.exec(selected_deviceId, res => {
                if(!res.error){
                    const eventChannel = this.getOpenerEventChannel();
                    eventChannel.emit("printSuccess");
                    wx.setStorageSync(self.BLEPrinter_device_name, selected_deviceId);
                }else{
                    self.showMessage("打印失败：", res.message);
                }
            });
        }else{
            this.showMessage("未选择打印设备");
        }
    },
    //处理数据
    translateQueueData_ing: false,
    translateQueueData(index){
        if(this.translateQueueData_ing) return;
        let self = this;
        index = index || 0;
        if(index <= this.printer.queue_data.length-1){
            let item = this.printer.queue_data[index];
            if(item.type === "image"){
                //图片
                //直接往下一个
                self.translateQueueData(index + 1);
            }else if(item.type === "qrcode") {
                //二维码数据，需要先生成二维码，再转换为图片
                drawQrcode({
                    canvasId: "qrcode",
                    text: item.data,
                    width: 200,
                    height: 200,
                    callback: () => {
                        //可能需要延迟
                        wx.canvasGetImageData({
                            canvasId: "qrcode",
                            x: 0,
                            y: 0,
                            width: 200,
                            height: 200,
                            success: res => {
                                //res.data
                                self.printer.queue.push.apply(self.printer.queue, self.printer.convertUint8ClampedArray(res.data));
                                self.translateQueueData(index + 1);
                            },
                            fail: () => {
                                //直接往下一个
                                self.translateQueueData(index + 1);
                            }
                        });
                    }
                });
            }else{
                //常规数据
                this.printer.queue.push.apply(this.printer.queue, Array.from(typeof item.data == "object" ? item.data : (typeof item.data == "function" ? item.data() : this.printer.encodeData(item.data))));
                //下一条
                this.translateQueueData(index + 1);
            }
        }else{
            //处理完成，开始打印
            this.translateQueueData_ing = false;
            this.translateQueueDataFinish = true;
            this.exec();
        }
    }
})
